/*
 * Created on Sat Sep 23 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import { createError } from './ErrorUtils';
import { ErrorCode } from '../constants';
import AuthService from '../services/auth';

const UID_KEY = '_CONTEXT_REQ_CURRENT_UID_KEY';

export function resolveToken(ctx: Object): string {
  if (!ctx.header || !ctx.header.authorization) {
    throw createError(401, '缺少认证头部', ErrorCode.REQUIRE_AUTHORIZATION_HEADER);
  }

  const parts = ctx.header.authorization.split(' ');

  if (parts.length === 2) {
    const scheme = parts[0];
    const credentials = parts[1];

    if (/^Bearer$/i.test(scheme)) {
      return credentials;
    }
  }

  throw createError(401, 'token格式错误', ErrorCode.TOKEN_INVALID);  
}

export let authenticationMiddleware = async (ctx: Object, next: Function) => { 
  let token = resolveToken(ctx);
  let payload = await AuthService.parseToken(token);
  ctx[UID_KEY] = payload.uid;
  await next();
};

export function getCurrentUidFromCtx(ctx: any): string {
  return ctx[UID_KEY];
}
